<template>
	<el-dialog title="选择人员" v-bind="dialogConfig" :visible.sync="visible">
		<div class="query_user_wrapper">
			<el-form size="mini" inline>
				<el-form-item><el-input v-model="queryUser.account" clearable placeholder="用户账号" style="width: 180px" /></el-form-item>
				<el-form-item><el-input v-model="queryUser.userName" clearable placeholder="用户姓名" style="width: 180px" /></el-form-item>
				<el-form-item><sw-dict-select v-model="queryUser.type" dict-name="USER_TYPE" clearable placeholder="用户类型" /></el-form-item>
				<el-form-item><sw-dict-select v-model="queryUser.sex" dict-name="USER_SEX" clearable placeholder="用户性别" /></el-form-item>
				<el-form-item><el-button type="primary" @click="queryTableData()">查询</el-button></el-form-item>
			</el-form>
			<el-table v-bind="tableConfig" :data="tableData" @row-click="handleRowClick" @select="handleSelectTable" @select-all="handleAllSelectTable">
				<el-table-column type="selection" width="48" align="center"></el-table-column>
				<el-table-column label="用户账号" prop="account" min-width="200"></el-table-column>
				<el-table-column label="用户姓名" prop="userName" min-width="200"></el-table-column>
				<el-table-column label="用户性别" width="100" align="center" :formatter="returnUserSexName" />
				<el-table-column label="用户类型" width="100" align="center" :formatter="returnUserTypeName" />
			</el-table>
			<sw-pagination :layout="pageLayout" :total="dataCount" :page.sync="queryUser.page" :limit.sync="queryUser.limit" @change="queryTableData" />
		</div>
		<div class="selected_user_box">
			<el-scrollbar>
				<div class="item" v-for="(item, index) in checkedUser" :key="index">
					<el-avatar size="medium" shape="square" :src="squareUrl"></el-avatar>
					<h4>{{ item.userName }}</h4>
					<el-button size="medium" type="text" icon="el-icon-delete" @click="handleDeleteUser(index)"></el-button>
				</div>
			</el-scrollbar>
			<div class="button">
				<el-button size="small" @click="visible = false">取消</el-button>
				<el-button size="small" type="primary" @click="handleSubmitUser">确定</el-button>
			</div>
		</div>
	</el-dialog>
</template>

<script>
import lodash from 'lodash';
import { mapGetters } from 'vuex';
import { getUserList } from '@/api/system/tbSysUser';
export default {
	props: {
		value: { type: Boolean, default: false },
		list: { type: Array, default: () => [] }
	},
	data() {
		return {
			visible: this.value,
			dialogConfig: {
				top: '0',
				width: '992px',
				appendToBody: true,
				customClass: 'select_user_dialog'
			},
			tableConfig: {
				ref: 'table',
				rowKey: 'id',
				size: 'medium',
				height: '100%'
			},
			squareUrl: require('@/assets/img/avatar_image.png'),
			pageLayout: 'slot, prev, pager, next',
			queryUser: { page: 1, limit: 10 },
			checkedUser: [],
			tableData: [],
			dataCount: 0
		};
	},
	computed: { ...mapGetters(['dictEnums']) },
	watch: {
		value(flag) {
			this.visible = flag;
		},
		visible(flag) {
			this.$emit('input', flag);
			if (!flag) return false;
			this.initSelectedUser();
			this.queryTableData();
		}
	},
	methods: {
		//初始化用户选中
		initSelectedUser() {
			this.checkedUser = lodash.cloneDeep(this.list);
		},

		//获取用户列表数据
		async queryTableData() {
			let params = { ...this.queryUser };
			let result = await getUserList(params).then((res) => res.data);
			if (result.code === '0') {
				this.dataCount = parseInt(result.count);
				this.tableData = result.data || [];
				this.configSelected(this.tableData);
			}
		},

		configSelected(arr) {
			this.$nextTick(() => {
				this.$refs['table'].clearSelection();
				this.checkedUser.forEach((item) => {
					let node = arr.find((n) => n.id === item.id);
					node && this.$refs['table'].toggleRowSelection(node, true);
				});
			});
		},

		//返回用户性别名称
		returnUserSexName(row) {
			let attrs = { size: 'small' };
			let userSexs = this.dictEnums['USER_SEX'] || [];
			let info = userSexs.find((n) => n.value === row.sex);
			return this.$createElement('elTag', { attrs }, info?.msg || '未知');
		},

		//返回用户类型名称
		returnUserTypeName(row) {
			let attrs = { size: 'small' };
			let userTypes = this.dictEnums['USER_TYPE'] || [];
			let info = userTypes.find((n) => n.value === row.type);
			return this.$createElement('elTag', { attrs }, info?.msg || '未知');
		},

		//行点击事件
		handleRowClick(data, column) {
			if (column.type === 'selection') return false;
			if (lodash.some(this.checkedUser, { id: data.id })) {
				let index = lodash.findIndex(this.checkedUser, { id: data.id });
				this.$refs['table'].toggleRowSelection(data, false);
				this.$delete(this.checkedUser, index);
			} else {
				this.checkedUser.push(lodash.pick(data, ['id', 'userName']));
				this.$refs['table'].toggleRowSelection(data, true);
			}
		},

		//单选用户数据
		handleSelectTable(selection, data) {
			if (lodash.some(this.checkedUser, { id: data.id })) {
				let index = lodash.findIndex(this.checkedUser, { id: data.id });
				this.$delete(this.checkedUser, index);
			} else {
				this.checkedUser.push(lodash.pick(data, ['id', 'userName']));
			}
		},

		//全选用户数据
		handleAllSelectTable(selection) {
			if (lodash.isEmpty(selection)) {
				this.tableData.forEach((item) => {
					let index = lodash.findIndex(this.checkedUser, { id: item.id });
					index !== -1 && this.$delete(this.checkedUser, index);
				});
			} else {
				selection.forEach((item) => {
					if (lodash.some(this.checkedUser, { id: item.id })) return false;
					this.checkedUser.push(lodash.pick(item, ['id', 'userName']));
				});
			}
		},

		//删除用户数据
		handleDeleteUser(index) {
			let user = this.checkedUser[index];
			this.$delete(this.checkedUser, index);
			this.$nextTick(() => {
				let node = this.tableData.find((n) => n.id === user.id);
				node && this.$refs['table'].toggleRowSelection(node, false);
			});
		},
		handleSubmitUser() {
			let added = lodash.differenceWith(this.checkedUser, this.list, lodash.isEqual);
			let deleted = lodash.differenceWith(this.list, this.checkedUser, lodash.isEqual);
			this.$emit('submit', this.checkedUser, added, deleted);
		}
	}
};
</script>
<style lang="scss">
.select_user_dialog .el-dialog__body {
	padding: 0;
	height: min(calc(100vh - 117px), 610px);
}
</style>
<style lang="scss" scoped>
.query_user_wrapper {
	display: flex;
	flex-direction: column;
	justify-content: space-between;
	overflow: hidden;
	padding: 12px;
	flex: 1;
	.el-form {
		display: flex;
		flex-shrink: 0;
		margin-bottom: 12px;
	}
	&:deep(.el-form-item) {
		margin-bottom: 0;
		&:last-child {
			margin-right: 0;
		}
	}
	&:deep(.el-form-item__content) {
		line-height: 1;
	}
	.el-table {
		flex: 1;
		margin-bottom: 12px;
		border: solid 1px #ebeef5;
		border-bottom: 0;
	}
	&:deep(.el-table__row) {
		cursor: pointer;
		user-select: none;
	}
	&:deep(th.el-table__cell) {
		background-color: var(--primary-background-plain-disabled);
		.cell {
			display: block;
			line-height: 1;
			font-size: 14px;
			color: #606266;
		}
	}
}
.selected_user_box {
	display: flex;
	flex-direction: column;
	border-left: solid 1px #e4e7ed;
	flex-shrink: 0;
	width: 240px;
	.el-scrollbar {
		flex: 1;
		overflow: hidden;
	}
	.item {
		display: flex;
		align-items: center;
		padding: 5px 10px;
		h4 {
			flex: 1;
			overflow: hidden;
			margin-left: 10px;
		}
	}
	&:deep(.el-scrollbar__view) {
		padding: 5px 0;
	}
	.button {
		padding: 10px;
		flex-shrink: 0;
		text-align: right;
		border-top: solid 1px #e4e7ed;
	}
}
</style>
